package stardust.product.platform.persistence.transaction;

import java.sql.SQLException;
import java.util.Stack;

import stardust.product.platform.persistence.DataAccessFactory;
import stardust.product.platform.persistence.PersistenceException;


public class TransactionManager
{
	
	private DataAccessFactory dataAccessFactory;

	private Stack<TransactionObject> transactionObjects = new Stack<TransactionObject>();
	
	public TransactionManager(DataAccessFactory dataAccessEntity)
	{
		this.dataAccessFactory = dataAccessEntity;
	}
	
	public TransactionObject beginTransaction() throws PersistenceException, SQLException
	{
		return this.beginTransaction(TransactionType.Supports);
	}
	
	public TransactionObject beginTransaction(TransactionType type) throws PersistenceException, SQLException
	{
		TransactionObject ta = new TransactionObject(this, new TransactionProperties(type));
		
		ta.begin();
		
		return ta;
	}
	
	public void commit() throws PersistenceException, SQLException
	{
		TransactionObject transactionObject;
		
		while ((transactionObject = this.getTransaction()) != null)
		{
			transactionObject.commit();
		}
	}
	
	public void rollback() throws PersistenceException, SQLException
	{
		TransactionObject transactionObject;
		
		while ((transactionObject = this.getTransaction()) != null)
		{
			transactionObject.rollback();
		}
	}
	
	public DataAccessFactory getDataAccessFactory()
	{
		return this.dataAccessFactory;
	}
	
	public TransactionObject getTransaction()
	{
		if (transactionObjects.isEmpty())
		{
			return null;
		}
		
		return transactionObjects.peek();
	}
	
	public int getTransactionCount()
	{
		return this.transactionObjects.size();
	}
	
	protected void registerTransaction(TransactionObject transactionObject)
	{
		this.transactionObjects.push(transactionObject);
	}
	
	protected TransactionObject deregisterTransaction()
	{
		return this.transactionObjects.pop();
	}
	
}
